import { getUserInfoAxios, queryBaseDictInfoAxios } from '@/api/user';
import { type AppStore, useAppStore } from '@/pinia/app';
import { mpLogin } from '@/utils/mp';
import { mpLoginRegisterAxios, refreshTokenAxios } from '@/api/account';
/**
 * 更新基础信息
 * @param isErrReturnSuccess - 错误时是否也强制返回成功
 */
export async function updateUserInfo(isErrReturnSuccess = true) {
  const appStore = useAppStore();
  if (appStore.loginState) {
    try {
      const dictRes = await getUserInfoAxios(appStore.access_token);
      appStore.setUserInfo(dictRes.data);
      return Promise.resolve(true);
    } catch (error) {
      // 防止报错
      return Promise.resolve(true);
    }
  } else {
    return Promise.resolve(isErrReturnSuccess);
  }
}

/** 自动登录的队列 */
let loginList: ((res: boolean) => void)[] = [];
let logining = false;
/**
 * 自动登录
 */
export function autoLogin(): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
    loginList.push((state) => {
      state ? resolve(true) : reject(false);
    });
    if (!logining) {
      logining = true;
      login()
        .then((res) => {
          loginList.forEach((cb) => {
            cb(res);
          });
          logining = false;
          loginList = [];
        })
        .catch(() => {
          loginList.forEach((cb) => {
            cb(false);
          });
          logining = false;
          loginList = [];
        });
    }
  });
}

/**
 * 自动登录
 */
async function login() {
  const appStore: AppStore = useAppStore();
  /** 是否为小程序平台 */
  let isMp = false;
  // #ifdef MP
  isMp = true;
  // #endif
  try {
    if (isMp) {
      await mpAutoLogin(appStore);
    } else {
      await appAutoWebLogin(appStore);
    }
    return Promise.resolve(true);
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 小程序自动登录
 */
async function mpAutoLogin(appStore: AppStore) {
  try {
    appStore.setIsLoginLoging(true);
    const mpLoginInfo = await mpLogin();
    const loginInfo = await mpLoginRegisterAxios({
      code: mpLoginInfo.code,
      channelId: appStore.launchQuery.channelId || undefined,
      referralLinkId: appStore.launchQuery.referralLinkId || undefined,
      clickid: appStore.launchQuery.clickid || undefined,
      launchQuery: JSON.stringify(appStore.launchQuery || {}),
      projectId: appStore.launchQuery.projectid || undefined,
      promotionId: appStore.launchQuery.promotionid || undefined,
      wxFinderId: appStore.launchQuery.wxFinderId || undefined,
      iaaFlag: appStore.launchQuery.iaaFlag || 0,
      launchQueryPramas: appStore.newLaunchQuery || {},
    });
    appStore.setAccessToken(loginInfo.data.accessToken || '');
    appStore.setRefreshToken(loginInfo.data.refreshToken || '');
    appStore.setPrivateKeyStr(loginInfo.data.privateKeyStr || '');
    const [userRes, dictRes] = await Promise.all([getUserInfoAxios(loginInfo.data.accessToken), queryBaseDictInfoAxios()]);
    appStore.setUserInfo(userRes.data);
    appStore.setBaseDictInfo(dictRes.data);
    appStore.setIsLoginLoging(false);
    return Promise.resolve(true);
  } catch (error) {
    console.log('静默登录失败====', error);
    appStore.setIsLoginLoging(false);
    appStore.logOut();
    return Promise.reject(error);
  }
}

/**
 * App 和 web 自动登录
 */
async function appAutoWebLogin(appStore: AppStore) {
  if (appStore.refresh_token) {
    try {
      appStore.setIsLoginLoging(true);
      const res = await refreshTokenAxios(appStore.refresh_token || '');
      appStore.setAccessToken(res.data.accessToken || '');
      appStore.setRefreshToken(res.data.refreshToken || '');
      appStore.setPrivateKeyStr(res.data.privateKeyStr || '');
      const [userRes, dictRes] = await Promise.all([getUserInfoAxios(res.data.accessToken), queryBaseDictInfoAxios()]);
      appStore.setUserInfo(userRes.data);
      appStore.setBaseDictInfo(dictRes.data);
      appStore.setIsLoginLoging(false);
      return Promise.resolve(true);
    } catch (error) {
      console.log('静默登录失败====', error);
      appStore.setIsLoginLoging(false);
      appStore.logOut();
      return Promise.reject(error);
    }
  } else {
    return Promise.reject({ code: -1001, msg: '从未登录或登录已失效' });
  }
}
